<template>
  <div style="overflow-x: hidden; overflow-y: auto; height: 95%">
    <!-- 已排区 -->
    <div id="alreadyOrdered3">
      <a-form
        ref="formRef2"
        size="small"
        :model="pageData"
        layout="inline"
        style="margin-left: 24px"
      >
        <!-- <a-form-item label="车间">
                    <a-select v-model="pageData.workshopId2" style="width: 120px" class="bacClass" allow-clear>
                        <a-option :value="1">染部A</a-option>
                        <a-option :value="2">染部B</a-option>
                    </a-select>
                </a-form-item> -->
        <a-form-item label="工段">
          <a-select
            style="width: 120px"
            class="bacClass"
            @search="sectionSearch()"
            @change="processSearch2()"
            v-model="pageData.sectionName2"
            allow-search
            allow-clear
          >
            <a-option
              v-for="item in pageData.sectionNameList"
              :value="item.sectionName"
              :key="item"
              >{{ item.sectionName }}</a-option
            >
          </a-select>
        </a-form-item>
        <a-form-item label="工序">
          <a-select
            style="width: 120px"
            class="bacClass"
            @search="processSearch2()"
            v-model="pageData.processId2"
            allow-search
            allow-clear
          >
            <a-option v-for="item in pageData.processList2" :value="item.id" :key="item">{{
              item.processName
            }}</a-option>
          </a-select>
        </a-form-item>
        <a-form-item label="流转卡号">
          <a-input
            allow-clear
            style="width: 120px"
            class="bacClass"
            v-model="pageData.flowCardCode2"
          />
        </a-form-item>
        <a-form-item label="状态">
          <a-input
            allow-clear
            style="width: 120px"
            class="bacClass"
            v-model="pageData.flowCardStatus"
          />
        </a-form-item>
        <a-form-item label="时间">
          <a-range-picker style="width: 247px" class="bacClass" v-model="pageData.dateTime2" />
        </a-form-item>
        <div style="display: flex">
          <a-button type="primary" style="margin-right: 28px" @click="doRefresh2()">查询</a-button>
          <a-button type="outline" style="margin-right: 28px" @click="editOrder()">修改</a-button>
        </div>
      </a-form>
      <div class="divInterval"></div>
      <div class="divCenter">
        <a-button class="buttonLeft" type="primary">已<br />排<br />区</a-button>
        <a-spin :loading="pageData.pageLoading2" tip="加载中" dot style="width: 95%; z-index: 999">
          <AgGridVuesCopys
            :rowHeight="33"
            :headerHeight="33"
            :suppressCopyRowsToClipboard="true"
            style="height: 400px; width: 100%"
            :suppressDragLeaveHidesColumns="true"
            rowSelection="multiple"
            @grid-ready="gridReady2"
            :defaultColDef="defaultColDef"
            class="ag-theme-alpine"
            :rowData="pageData.arrangedList"
            :columnDefs="tableColumns2"
            :localeText="localeText1"
            :rowDragManaged="true"
            :animateRows="true"
            @rowDragEnd="onRowDragEnd"
          >
          </AgGridVuesCopys>
        </a-spin>
      </div>
    </div>
    <!-- 调转位置图标按钮 -->
    <div id="gang3">
      <icon-double-down
        @click="transferDown()"
        style="margin-left: 50%"
        :strokeWidth="3"
        :size="22"
      />
    </div>
    <!-- 未排区 -->
    <div id="notOrdered3">
      <a-form
        ref="formRef"
        size="small"
        :model="pageData"
        layout="inline"
        style="margin-left: 24px"
      >
        <!-- <a-form-item label="车间">
                    <a-select v-model="pageData.workshopId" style="width: 120px" class="bacClass" allow-clear>
                        <a-option :value="1">染部A</a-option>
                        <a-option :value="2">染部B</a-option>
                    </a-select>
                </a-form-item> -->
        <a-form-item label="工段">
          <a-select
            style="width: 120px"
            class="bacClass"
            @search="sectionSearch()"
            @change="processSearch()"
            v-model="pageData.sectionName"
            allow-search
            allow-clear
          >
            <a-option
              v-for="item in pageData.sectionNameList"
              :value="item.sectionName"
              :key="item"
              >{{ item.sectionName }}</a-option
            >
          </a-select>
        </a-form-item>
        <a-form-item label="工序">
          <a-select
            style="width: 120px"
            class="bacClass"
            @search="processSearch()"
            v-model="pageData.processId"
            allow-search
            allow-clear
          >
            <a-option v-for="item in pageData.processList" :value="item.id" :key="item">{{
              item.processName
            }}</a-option>
          </a-select>
        </a-form-item>
        <a-form-item label="流转卡号">
          <a-input
            allow-clear
            style="width: 120px"
            class="bacClass"
            v-model="pageData.flowCardCode"
          />
        </a-form-item>
        <a-form-item label="流转状态">
          <a-input
            allow-clear
            style="width: 120px"
            class="bacClass"
            v-model="pageData.flowCardStatus"
          />
        </a-form-item>
        <a-button type="primary" style="margin-right: 28px" @click="doRefresh()">查询</a-button>
        <a-form-item label="排产时间">
          <a-range-picker style="width: 247px" class="bacClass" v-model="pageData.dateTime" />
        </a-form-item>
        <a-form-item label="已排">
          <a-input style="width: 70px" class="bacClass" v-model="pageData.arrangedSum" disabled />
        </a-form-item>
        <a-form-item label="未排">
          <a-input
            style="width: 70px"
            class="bacClass"
            v-model="pageData.unscheduledSum"
            disabled
          />
        </a-form-item>
      </a-form>
      <div class="divInterval"></div>
      <div class="divCenter">
        <a-button class="buttonLeft" type="primary" style="margin-top: -10px"
          >未<br />排<br />区</a-button
        >
        <a-spin
          :loading="pageData.pageLoading"
          tip="加载中"
          dot
          style="width: 95%; z-index: 999; margin-bottom: 10px"
        >
          <AgGridVuesCopys
            :rowHeight="33"
            :headerHeight="33"
            :suppressCopyRowsToClipboard="true"
            style="height: 400px; width: 100%"
            :suppressDragLeaveHidesColumns="true"
            rowSelection="multiple"
            @grid-ready="gridReady"
            :defaultColDef="defaultColDef"
            class="ag-theme-alpine"
            :rowData="pageData.unscheduledList"
            :columnDefs="tableColumns"
            :localeText="localeText1"
          >
          </AgGridVuesCopys>
        </a-spin>
      </div>
    </div>
  </div>
  <!-- 排产弹窗 -->
  <a-drawer
    style="z-index: 999"
    ok-text="保存"
    cancel-text="关闭"
    :drawer-style="{ zIndex: 9999 }"
    :mask-closable="false"
    :visible="pageData.apsShow"
    :ok-loading="pageData.pageLoading"
    unmountOnClose
    placement="bottom"
    height="100%"
    @ok="apsOk"
    @cancel="pageData.apsShow = false"
  >
    <template #title>
      {{ pageData.sideTitle }}
    </template>
    <div>
      <!-- 机台排产 -->
      <AgGridVuesCopys
        :rowHeight="33"
        :headerHeight="33"
        :suppressCopyRowsToClipboard="true"
        style="height: 670px; width: 100%; margin-top: 5px; margin-bottom: 20px"
        :suppressDragLeaveHidesColumns="true"
        rowSelection="multiple"
        @grid-ready="apsGridReady"
        :defaultColDef="defaultColDef"
        class="ag-theme-alpine"
        :rowData="pageData.apsList"
        :columnDefs="aspTableColumns"
        :localeText="localeText1"
        :suppressMovableColumns="true"
      >
      </AgGridVuesCopys>
      <table class="table" v-if="pageData.sideTitle != '已排产顺序调整'">
        <thead>
          <tr>
            <th :colspan="12">流转卡工序时间计算</th>
          </tr>
          <tr style="background-color: #dde2eb">
            <th>原计划开始</th>
            <td>1月25日</td>
            <th>原计划结束</th>
            <td>1月25日</td>
            <th>调后开始</th>
            <td>1月26日</td>
            <th>调整后结束</th>
            <td>1月26日</td>
            <th>调整前状态</th>
            <td>1月25日</td>
            <th>调整后状态</th>
            <td>1月26日</td>
          </tr>
        </thead>
      </table>
    </div>
  </a-drawer>

  <a-drawer
    style="z-index: 999"
    ok-text="保存"
    cancel-text="关闭"
    :drawer-style="{ zIndex: 9999 }"
    :mask-closable="false"
    :visible="pageData.progressShow"
    :ok-loading="pageData.pageLoading2"
    unmountOnClose
    placement="bottom"
    height="100%"
    @ok="pageData.progressShow = false"
    @cancel="pageData.progressShow = false"
    :closable="false"
  >
    <template #title>生产进度查询</template>
    <a-table
      :pagination="false"
      :style="{
        height: '500px',
        marginTop: '10px',
        alignItems: 'center',
      }"
      column-resizable
      stripe
      :scrollbar="true"
      :bordered="{ cell: true }"
      sticky-header
      :columns="JDTableColumns"
      :data="pageData.progressList"
      :span-method="dataSpanMethod"
    >
      <template #optType="{ record }">
        <a-steps direction="vertical">
          <!-- 遍历 sectionNames -->
          <a-step v-for="item in uniqueSectionNames()" :key="item.sectionName">
            <template #icon>
              <div
                style="width: 28px; height: 28px; border-radius: 50%"
                :style="{
                  border:
                    item.optType == 0
                      ? '2px solid #707070'
                      : item.optType == 1
                      ? '2px solid #5191FD'
                      : '2px solid #00B050',
                }"
              >
              </div>
            </template>
          </a-step>
        </a-steps>
      </template>
      <template #processName="{ record }">
        <div
          class="status-point"
          :style="{
            backgroundColor:
              record.optType == 0 ? '#707070' : record.optType == 1 ? '#5191FD' : '#00B050',
          }"
        ></div
        >{{ record.processName }}
      </template>
    </a-table>
  </a-drawer>
</template>

<script lang='ts' setup>
import { reactive, toRefs, ref, onMounted } from 'vue'
import Toolbar from '@/components/Toolbar.vue'
import { post, get } from '@/api/http'
import { FormInstance, Message, Modal } from '@arco-design/web-vue'

import { localeText } from '@/api/aggridZw'
import { pagingList } from '@/api/paging'

const pagingList1: any = ref(pagingList)
const localeText1: any = ref(localeText)
const pageData: any = reactive({
  apsShow: false,
  sideTitle: '',
  rHeight: 0,
  arrangedList: [],
  unscheduledList: [],
  flowList: [],
  apsList: [],
  pageLoading: false,
  pageLoading2: false,
  arrangedSum: '',
  onePlace: '',
  twoPlace: '',
  unscheduledSum: '',
  working: '',
  free: '',
  workshopId: null,
  workshopId2: null,
  flowCardCode: '',
  flowCardCode2: '',
  machineList: [],
  typeList: [],
  dateTime: [],
  dateTime2: [],
  processId: null,
  processId2: null,
  processList: [],
  processList2: [],
  sectionName: '',
  sectionName2: '',
  sectionNameList: [],
  progressShow: false,
  progressList: [],
})

const dataForm: any = reactive({
  flowCardCode: '',
  scheduleDates: [],
  workshopId: null,
})

const defaultColDef: any = {
  sortable: true,
  resizable: true,
  filter: true,
}

// 未排产表格
const gridOption = ref()
const gridReady = (params: any) => {
  gridOption.value = params.api
}
let tableColumns: any = [
  { headerName: '工段', field: 'sectionName', width: 100 },
  { headerName: '工序', field: 'processName', width: 100 },
  { headerName: '流转状态', field: 'cardState', width: 100 },
  {
    headerName: '色样',
    field: 'colorSample',
    width: 100,
    cellRenderer: {
      template: ` <a-image v-if="val.colorSample" :src="val.colorSample" /> 
                      <span v-if="!val.colorSample"></span>`,
      setup(props: any) {
        const val = ref(props.params.data)
        return {
          val,
        }
      },
    },
  },
  { headerName: '色称', field: 'colorName', width: 100 },
  { headerName: '流转卡号', field: 'flowCardCode', width: 100 },
  { headerName: '匹数', field: 'houseNum', width: 100 },
  { headerName: '重量(KG)', field: 'flowCardWeight', width: 100 },
  { headerName: '色号', field: 'colorCode', width: 100 },
  { headerName: '客户', field: 'customName', width: 100 },
  { headerName: '品牌', field: 'dd', width: 100 },
  { headerName: '布名', field: 'clothCode', width: 100 },
  { headerName: '衫款', field: 'dd', width: 100 },
  { headerName: '订单类型', field: 'dd', width: 100 },
  { headerName: '流转卡类型', field: 'dd', width: 100 },
  {
    headerName: 'HOLD单状态',
    field: 'holdState',
    width: 100,
    cellRenderer: {
      template: `<div>{{ val.holdState == 0 ? '否' : '是' }}</div>`,
      setup(props: any) {
        let val = ref(props.params.data)
        return {
          val,
        }
      },
    },
    filterParams: {
      valueFormatter: function (params: any) {
        return params.value == 0 ? '否' : params.value == 1 ? '是' : ''
      },
    },
  },
  { headerName: '交期', field: 'deliveryTime', width: 100 },
  { headerName: '计划开始', field: 'dd', width: 100 },
  { headerName: '计划结束', field: 'dd', width: 100 },
  { headerName: '备注', field: 'remark', width: 100 },
  {
    headerName: '工艺流程',
    //工序动态表头
    children: [],
  },
  {
    headerName: '操作',
    field: 'action',
    width: 100,
    pinned: 'right',
    cellRenderer: {
      template: `<a-button type="primary" size="mini" @click="c">排产</a-button>`,
      setup(props: any) {
        const c = () => {
          apsMethod(props.params.data)
        }
        return {
          c,
        }
      },
    },
  },
]

// 已排产表格
const gridOption2 = ref()
const gridReady2 = (params: any) => {
  gridOption2.value = params.api
}
let tableColumns2: any = [
  {
    field: '',
    pinned: 'left',
    rowDrag: (params: any) => {
      return !(params.data.machineOrder == null)
    },
    width: 50,
  },
  { headerName: '工段', field: 'sectionName', width: 100 },
  { headerName: '工序', field: 'processName', width: 100 },
  // { headerName: '车间', field: 'workshop', width: 100 },
  { headerName: '排产时间', field: 'scheduledTime', width: 100 },
  { headerName: '排位', field: 'machineOrder', width: 100 },
  {
    headerName: '色样',
    field: 'colorSample',
    width: 100,
    cellRenderer: {
      template: ` <a-image v-if="val.colorSample" :src="val.colorSample" /> 
                      <span v-if="!val.colorSample"></span>`,
      setup(props: any) {
        const val = ref(props.params.data)
        return {
          val,
        }
      },
    },
  },
  { headerName: '色称', field: 'colorName', width: 100 },
  { headerName: '流转卡号', field: 'flowCardCode', width: 100 },
  { headerName: '匹数', field: 'houseNum', width: 100 },
  { headerName: '重量(KG)', field: 'flowCardWeight', width: 100 },
  { headerName: '色号', field: 'colorCode', width: 100 },
  { headerName: '客户', field: 'customName', width: 100 },
  { headerName: '品牌', field: 'dd', width: 100 },
  { headerName: '布名', field: 'clothCode', width: 100 },
  { headerName: '衫款', field: 'dd', width: 100 },
  { headerName: '流转卡类型', field: 'dd', width: 100 },
  {
    headerName: 'HOLD单状态',
    field: 'holdState',
    width: 100,
    cellRenderer: {
      template: `<div>{{ val.holdState == 0 ? '否' : '是' }}</div>`,
      setup(props: any) {
        let val = ref(props.params.data)
        return {
          val,
        }
      },
    },
    filterParams: {
      valueFormatter: function (params: any) {
        return params.value == 0 ? '否' : params.value == 1 ? '是' : ''
      },
    },
  },
  { headerName: '交期', field: 'deliveryTime', width: 100 },
  { headerName: '计划开始', field: 'dd', width: 100 },
  { headerName: '计划结束', field: 'dd', width: 100 },
  { headerName: '备注', field: 'remark', width: 100 },
  { headerName: '工艺流程', children: [] },
  {
    headerName: '操作',
    field: 'action',
    width: 100,
    pinned: 'right',
    cellRenderer: {
      template: `<a-button type="primary" size="mini" @click="c">进度跟踪</a-button>`,
      setup(props: any) {
        const c = () => {
          progressTracking(props.params.data)
        }
        return {
          c,
        }
      },
    },
  },
]

//机台排产表格
const apsGridOption = ref()
const apsGridReady = (params: any) => {
  apsGridOption.value = params.api
}
const aspTableColumns: any = ref([])

//进度跟踪表格
const JDGridOption = ref()
const JDGridReady = (params: any) => {
  JDGridOption.value = params.api
}
const JDTableColumns = reactive([
  { title: '状态', key: 'optType', dataIndex: 'optType', slotName: 'optType', width: 120 },
  { title: '完成时间', key: 'finishTime', dataIndex: 'finishTime', width: 120 },
  { title: '工段', key: 'sectionName', dataIndex: 'sectionName', width: 120 },
  {
    title: '工序',
    key: 'processName',
    dataIndex: 'processName',
    slotName: 'processName',
    width: 120,
  },
  {
    title: '完成统计',
    children: [
      { title: '计划完成', key: 'null', dataIndex: 'null', width: 120 },
      { title: '实际完成', key: 'finishTime', dataIndex: 'finishTime', width: 120 },
      { title: '完成人员', key: 'finishEmployee', dataIndex: 'finishEmployee', width: 120 },
      { title: '耗时', key: 'id', dataIndex: 'id', width: 120 },
      // {
      //   title: '耗时',
      //   width: 120,
      //   cellRenderer: (params: any) => {
      //     params.finishTime = '2024-01-01 20:00:00'
      //     params.startTime = '2024-01-01 21:00:00'
      //     if (params.finishTime && params.startTime) {
      //       console.log(params.finishTime - params.startTime, 'startTime')
      //       let val = params.finishTime - params.startTime
      //       return '<span>' + val + '</span>'
      //     } else {
      //       return '<span>' + '' + '</span>'
      //     }
      //   },
      // },
    ],
  },
  {
    title: '异常记录',
    children: [
      { title: '异常原因', key: 'exceptionDesc', dataIndex: 'exceptionDesc', width: 120 },
      { title: '处理方式', key: 'resolution', dataIndex: 'resolution', width: 120 },
      { title: '承接工序', key: 'null', dataIndex: 'null', width: 120 },
      { title: '处理人', key: 'handler', dataIndex: 'handler', width: 120 },
    ],
  },
])

//未排区 查询
function doRefresh() {
  if (pageData.sectionName && !pageData.processId) {
    Message.warning('请选择工序!')
    return
  }
  pageData.pageLoading = true
  get({
    url: 'aps/workSequenceTask/findTaskByProcessAndStatus',
    data: {
      status: 0,
      flowCardCode: pageData.flowCardCode,
      processId: pageData.processId,
    },
  })
    .then(({ data, code }: any) => {
      if (code === 200) {
        columnsName(tableColumns, data)
        tableColumns = [...tableColumns]
        pageData.unscheduledList = data
        pageData.unscheduledSum = pageData.unscheduledList.length
        gridOption.value.setRowData(data)
      }
    })
    .catch(console.log)
    .finally(() => {
      pageData.pageLoading = false
    })
}

//已排区 查询
function doRefresh2() {
  if (pageData.sectionName2 && !pageData.processId2) {
    Message.warning('请选择工序!')
    return
  }
  pageData.pageLoading2 = true
  get({
    url: 'aps/workSequenceTask/findTaskByProcessAndStatus',
    data: {
      status: 1,
      flowCardCode: pageData.flowCardCode2,
      beginDate: pageData.dateTime2 ? pageData.dateTime2[0] : null,
      endDate: pageData.dateTime2 ? pageData.dateTime2[1] : null,
      processId: pageData.processId2,
    },
  })
    .then(({ data, code }: any) => {
      if (code === 200) {
        columnsName(tableColumns2, data)
        tableColumns2 = [...tableColumns2]
        pageData.arrangedList = data
        pageData.arrangedSum = pageData.arrangedList.length
        pageData.onePlace = pageData.arrangedList.filter((o: any) => o.machineOrder == 1).length
        pageData.twoPlace = pageData.arrangedList.filter((o: any) => o.machineOrder == 2).length
        gridOption2.value.setRowData(data)
      }
    })
    .catch(console.log)
    .finally(() => {
      pageData.pageLoading2 = false
    })
}

// 自定义的单元格渲染器
const customCellRenderer = (params: any) => {
  const flowList = params.data.flowList
  const isExists = flowList && flowList.includes(params.colDef.headerName)
  return isExists ? 'Y' : 'N'
}

// 定义样式函数
const customCellStyle = (params: any) => {
  const flowList = params.data.flowList
  const isExists = flowList && flowList.includes(params.colDef.headerName)
  return isExists ? { backgroundColor: '#64dd3f' } : { backgroundColor: '#b7b3b3' }
}

//工艺流程动态获取子表头数据
const columnsName = (columns: any, data: any) => {
  const childColumns = columns.find((col: any) => col.headerName === '工艺流程')
  if (data.length > 0) {
    childColumns.children = data[0].processNames.map((name: any) => ({
      headerName: name,
      field: '',
      width: 100,
      cellRenderer: customCellRenderer,
      cellStyle: customCellStyle,
    }))
  } else {
    delete childColumns.children
  }
}

//排产 弹窗
const apsMethod = (val: any) => {
  dataForm.flowCardCode = val.flowCardCode + '_' + val.taskId
  dataForm.castNum = val.castNum
  dataForm.houseNum = val.houseNum
  dataForm.flowCardWeight = val.flowCardWeight
  dataForm.cylinderType = val.cylinderType
  pageData.sideTitle = '排产'
  if (pageData.dateTime.length === 0) {
    Message.warning('请先选择时间')
    return
  }
  workshopTask(val.processId, pageData.dateTime)
}

//已排产修改 弹窗
const editOrder = () => {
  dataForm.flowCardCode = ''
  pageData.sideTitle = '已排产顺序调整'
  if (!pageData.processId2) {
    Message.warning('请先选择工序')
    return
  }
  if (pageData.dateTime2.length === 0) {
    Message.warning('请先选择时间')
    return
  }
  workshopTask(pageData.processId2, pageData.dateTime2)
}

function formatDate(dateString: any) {
  const date = new Date(dateString)
  const month = date.getMonth() + 1
  const day = date.getDate()
  return `${month}月${day}日`
}

//排产  已排产顺序调整
const workshopTask = (processId: any, date: any) => {
  pageData.sideTitle == '排产' ? (pageData.pageLoading = true) : (pageData.pageLoading2 = true)
  get({
    url: 'aps/workSequenceTask/findWorkSequenceForScheduling',
    data: {
      processId: processId,
      beginDate: date[0],
      endDate: date[1],
    },
  }).then(({ code, data, message }) => {
    if (code == 200) {
      dataForm.scheduleDates = data.scheduleDates
      // 推荐机台 赋值
      let foundEmpty = false
      data.flowCardMachineMap.forEach((o: any) => {
        if (!foundEmpty && !o[data.recommendDate]) {
          o[data.recommendDate] = dataForm.flowCardCode
          foundEmpty = true
          //新增一行空白数据 可拖拽
          const newlist = {}
          data.scheduleDates.forEach((time: any) => {
            newlist[time] = ''
          })
          data.flowCardMachineMap.push(newlist)
        }
      })
      //如果推荐机台无位置，新增加一行数据push
      if (!foundEmpty) {
        const newObject = {}
        data.scheduleDates.forEach((time: any) => {
          newObject[time] = ''
        })
        newObject[data.recommendDate] = dataForm.flowCardCode
        data.flowCardMachineMap.push(newObject)
      }
      pageData.apsList = data.flowCardMachineMap

      //拖拽方法
      aspTableColumns.value = data.scheduleDates.map((res: any) => ({
        headerName: formatDate(res),
        field: res,
        minWidth: 39,
        width: 100,
        wrapHeaderText: true,
        autoHeaderHeight: true,
        cellStyle: (val: any) => {
          if (pageData.sideTitle == '排产' && val.value == dataForm.flowCardCode) {
            return { backgroundColor: 'skyblue' } //推荐机台底色为蓝色
          }
          return null // 保持原样
        },
        cellRenderer: {
          template: `<div style="width:100px;height:32px;text-align:center;" draggable="true" @dragstart="onDragStart"
                               @dragover="allowDrop" @drop="drop">{{ params.data[val] ? params.data[val].split('_')[0] : '' }}
                           </div>`,
          setup(props: any) {
            const val = ref(res)
            let isRecommendedMachine: any = props.params.data[val.value] == dataForm.flowCardCode // 检查是否是推荐机台列
            //根据条件 是否允许拖拽
            const onDragStart = (event: any) => {
              if (
                props.params.data[val.value] &&
                isRecommendedMachine &&
                pageData.sideTitle != '已排产顺序调整'
              ) {
                event.dataTransfer.setData(
                  'text/col/row',
                  JSON.stringify({
                    text: props.params.data[val.value],
                    col: val.value,
                    row: props.params.rowIndex,
                  })
                )
              } else if (props.params.data[val.value] && pageData.sideTitle == '已排产顺序调整') {
                event.dataTransfer.setData(
                  'text/col/row',
                  JSON.stringify({
                    text: props.params.data[val.value],
                    col: val.value,
                    row: props.params.rowIndex,
                  })
                )
              } else {
                event.preventDefault()
              }
            }
            // 是否允许放置拖拽的任务
            const allowDrop = (event: any) => {
              event.preventDefault()
            }
            // 放置任务时调用 获取拖拽的数据并处理
            const drop = (event: any) => {
              event.preventDefault()
              const droppedData = JSON.parse(event.dataTransfer.getData('text/col/row'))
              if (droppedData.col === val.value) {
                let oldCol = data.flowCardMachineMap.map((o: any) => o[droppedData.col])
                let oldLine = droppedData.row
                let desLine = props.params.rowIndex
                let arr = oldCol.splice(oldLine, 1)
                oldCol.splice(desLine, 0, arr[0])
                data.flowCardMachineMap.forEach((o: any, index: number) => {
                  o[val.value] = oldCol[index]
                })
              } else {
                let fromCol = data.flowCardMachineMap.map((o: any) => o[droppedData.col]) //原队列
                let toCol = data.flowCardMachineMap.map((o: any) => o[val.value]) //新队列
                let fromLine = droppedData.row //原行
                let desLine = props.params.rowIndex //目标行
                let arr = fromCol.splice(fromLine, 1) //删除原行拖动值
                toCol.splice(desLine, 0, arr[0]) //添加
                if (toCol[toCol.length - 1]) {
                  //最后一行数据时自动增加一行
                  const newObject = {}
                  data.scheduleDates.forEach((time: any) => {
                    newObject[time] = ''
                  })
                  newObject[data.recommendDate] = dataForm.flowCardCode
                  data.flowCardMachineMap.push(newObject)
                }

                data.flowCardMachineMap.forEach((o: any, index: number) => {
                  o[val.value] = toCol[index]
                  o[droppedData.col] = fromCol[index]
                })
              }
              pageData.apsList = data.flowCardMachineMap.filter((row: any) => {
                return Object.values(row).some((value) => value) //清除空行
              })
            }
            return {
              val,
              drop,
              allowDrop,
              onDragStart,
              isRecommendedMachine,
            }
          },
        },
      }))
      pageData.apsShow = true
      pageData.pageLoading = false
      pageData.pageLoading2 = false
    } else {
      Message.error(message)
    }
  })
}
const apsOk = () => {
  //判断机台中队列是否排满 中间不能有空格
  let invalid = false
  dataForm.scheduleDates.forEach((code: any) => {
    let firstPosi = -1
    let resList: any = [...pageData.apsList].reverse()
    resList.forEach((o: any, i: any) => {
      if (firstPosi == -1) {
        if (o[code]) {
          firstPosi = i
        }
      } else {
        if (!o[code]) {
          invalid = true
          return
        }
      }
    })
  })
  if (invalid) {
    Message.warning('任务时间队列中间未排满！')
    return
  }

  //保存
  pageData.pageLoading = true
  post({
    url: 'aps/workSequenceTask/updateTaskOrderAndDate',
    data: pageData.apsList.filter((row: any) => {
      return Object.values(row).some((value) => value !== '') // 检查每个属性是否都为空
    }),
  }).then(({ code, message }) => {
    if (code == 200) {
      Message.success('成功')
      pageData.apsShow = false
      pageData.pageLoading = false
      doRefresh()
      doRefresh2()
    } else {
      Message.error(message)
    }
  })
}

// 定义调换位置的方法
const transferDown = () => {
  const alreadyOrdered3: any = document.getElementById('alreadyOrdered3')
  const notOrdered3: any = document.getElementById('notOrdered3')
  const gang3: any = document.getElementById('gang3')
  // 获取两个元素的父级节点
  const parent = alreadyOrdered3.parentNode
  // 获取两个元素在父级节点中的位置索引
  const indexA = Array.from(parent.children).indexOf(alreadyOrdered3)
  const indexB = Array.from(parent.children).indexOf(notOrdered3)
  // 将notOrdered3插入到alreadyOrdered3之前
  parent.insertBefore(notOrdered3, alreadyOrdered3)
  // 将alreadyOrdered3插入到notOrdered3原来的位置
  if (indexA < indexB) {
    // 如果alreadyOrdered3原来在gang2之前，插入到gang3之前
    parent.insertBefore(alreadyOrdered3, gang3.nextSibling)
  } else {
    // 如果alreadyOrdered3原来在gang2之后，插入到gang3之后
    parent.insertBefore(alreadyOrdered3, gang3)
  }
}

// 顺序调整
const onRowDragEnd = (params: any) => {
  const { overIndex, node } = params
  const dragRowData = node.data
  const currentIndex = pageData.arrangedList.indexOf(dragRowData)
  pageData.arrangedList.splice(currentIndex, 1)
  pageData.arrangedList.splice(overIndex, 0, dragRowData)
  //查找拖动行相同的scheduledTime 和processId
  const dragMachineCode = dragRowData.scheduledTime
  const dragProcessId = dragRowData.processId
  const sameGroup = pageData.arrangedList.filter(
    (item: any) => item.scheduledTime === dragMachineCode && item.processId === dragProcessId
  )
  sameGroup.forEach((o: any, index: number) => {
    o.machineOrder = index + 1
  })
  //更新数组
  pageData.arrangedList = [...pageData.arrangedList]
  let list = pageData.arrangedList.filter(
    (o: any) => o.scheduledTime == dragMachineCode && o.processId === dragProcessId
  )
  let data: any = []
  list.forEach((o: any) => {
    let newData = { id: o.taskId, machineOrder: o.machineOrder }
    data.push(newData)
  })
  //实时更新顺序
  post({
    url: 'aps/workSequenceTask/updateTaskMachineOrder',
    data: data,
  }).then((res: any) => {
    if (res.code === 200) {
      doRefresh2()
    } else {
      Message.error(res.message)
    }
  })
}

//进度跟踪
const progressTracking = (val: any) => {
  pageData.progressShow = true
  get({
    url: '/aps/dwDefect/buildWorkProcessReport?flowCardCode=' + val.flowCardCode,
  }).then((res: any) => {
    if (res.code === 200) {
      pageData.progressList = res.data
    } else {
      Message.error(res.message)
    }
  })
}

//工段下拉框
const sectionSearch = () => {
  post({
    url: '/pdm/worksection/getFieldValue',
    data: {
      sectionName: pageData.sectionName,
    },
  }).then(({ data, code }: any) => {
    if (code === 200) {
      pageData.sectionNameList = data
    } else {
      Message.error({
        content: '查询失败！',
        duration: 5000,
      })
    }
  })
}

//工序下拉框
const processSearch = () => {
  pageData.processId = ''
  pageData.processList = []
  if (pageData.sectionName) {
    post({
      url: 'pdm/worksectionWorkprocedure/selectPage',
      data: {
        deleteState: 0,
        size: 10000,
        page: 1,
        sectionName: pageData.sectionName,
      },
    }).then(({ data, code }: any) => {
      if (code === 200) {
        pageData.processList = data.list
      }
    })
  }
}

const processSearch2 = () => {
  pageData.processId2 = ''
  pageData.processList2 = []
  if (pageData.sectionName2) {
    post({
      url: 'pdm/worksectionWorkprocedure/selectPage',
      data: {
        deleteState: 0,
        size: 10000,
        page: 1,
        sectionName: pageData.sectionName2,
      },
    }).then(({ data, code }: any) => {
      if (code === 200) {
        pageData.processList2 = data.list
      }
    })
  }
}

//合并单元格
const dataSpanMethod = ({ record, column, rowIndex }: any) => {
  if (column.dataIndex === 'optType') {
    return {
      rowspan: pageData.progressList.length,
    }
  }
  if (column.dataIndex === 'sectionName') {
    const sectionName = record.sectionName
    let rowspan = 1
    let currentIndex = rowIndex + 1
    // 向后搜索，直到遇到不同的 sectionName 或数组结束
    while (
      currentIndex < pageData.progressList.length &&
      pageData.progressList[currentIndex].sectionName === sectionName
    ) {
      rowspan++
      currentIndex++
    }
    return {
      rowspan: rowspan,
    }
  }
}

const uniqueSectionNames = () => {
  const sectionMap = new Map()
  pageData.progressList.forEach((item: any) => {
    if (sectionMap.has(item.sectionName)) {
      if (item.optType === 1) {
        sectionMap.set(item.sectionName, { sectionName: item.sectionName, optType: item.optType })
      }
    } else {
      sectionMap.set(item.sectionName, { sectionName: item.sectionName, optType: item.optType })
    }
  })
  console.log(Array.from(sectionMap.values()))
  return Array.from(sectionMap.values())
}

onMounted(() => {
  pageData.rHeight = document.getElementsByClassName('main-section')[0]?.clientHeight
  //弹出层的高
  if (pageData.rHeight !== undefined) {
    pageData.rHeight = pageData.rHeight
  }
  doRefresh()
  doRefresh2()
  sectionSearch()
})
</script>
<style lang='less' scoped>
:deep(.ag-cell) {
  border-right: 1px solid #dde2eb;
}

:deep(.ag-header-cell) {
  border-right: 1px solid #dde2eb;
}

:deep(.ag-cell-value) {
  user-select: initial;
  -moz-user-select: text;
  -ms-user-select: text;
  -webkit-user-select: text;
}

:deep(.arco-upload-progress) {
  display: none;
}

:deep(.arco-table-td-content) {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  font-size: 14px;
}

:deep(.arco-table-th-title) {
  color: black;
  font-weight: bold;
  font-size: 0.9rem;
}

:deep(.arco-steps-icon) {
  background: white;
}

#gang3 {
  height: 20px;
  margin-top: 20px;
  margin-bottom: 20px;
  background-color: #f0f2f5;
}

.divInterval {
  border: 2px solid #f0f2f5;
  width: 100%;
  height: 2px;
  margin-top: 10px;
  margin-bottom: 12px;
}

.buttonLeft {
  width: 0px;
  height: 400px;
  color: #fff;
}

.divCenter {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

:deep(.custom-header-class) {
  background-color: #fff !important;

  &:hover {
    background-color: #fff !important;
  }
}

.table {
  td,
  th {
    border: 1px solid #babfc7;
    text-align: center;
    padding: 8px;
  }
}

.status-point {
  display: inline-block;
  width: 10px;
  height: 10px;
  border-radius: 50%;
  margin-right: 5px;
}
</style>